﻿// Copyright (C) 2009 Choonghwan Lee (linjus.lee@gmail.com)
//
// This file is part of amanda.
//
// amanda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// amanda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with amanda. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace manager
{
	public class Shell
	{
		[StructLayout(LayoutKind.Sequential)]
		public struct BROWSEINFO
		{
			public IntPtr hwndOwner;
			public IntPtr pidlRoot;
			[MarshalAs(UnmanagedType.LPStr)]
			public String pszDisplayName;
			[MarshalAs(UnmanagedType.LPStr)]
			public String lpszTitle;
			public UInt32 ulFlags;
			[MarshalAs(UnmanagedType.FunctionPtr)]
			public BrowseCallbackProc lpfn;
			public Int32 lParam;
			public Int32 iImage;
		}

		public delegate Int32 BrowseCallbackProc(IntPtr hwnd, UInt32 uMsg, Int32 lParam, Int32 lpData);

		[DllImport("shell32.dll")]
		public static extern IntPtr SHBrowseForFolder(ref BROWSEINFO lbpi);

		[DllImport("shell32.dll")]
		public static extern Int32 SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);
	}

	public class ShellWrapper
	{
		public string Ask()
		{
			Shell.BROWSEINFO brinfo = new Shell.BROWSEINFO();
			brinfo.hwndOwner = IntPtr.Zero;
			brinfo.pidlRoot = IntPtr.Zero;
			IntPtr folder = Shell.SHBrowseForFolder(ref brinfo);
			if (folder == IntPtr.Zero)
				return null;

			StringBuilder path = new StringBuilder();
			if (Shell.SHGetPathFromIDList(folder, path) == 0)
				return null;
			return path.ToString();
		}
	}
}
